package com.wxit.algorithm.leetcode;

import com.wxit.algorithm.stack.ArraysStack;

/**
 * 有效的括号字符串
 */
public class E13LeetCode20 {
    public static void main(String[] args) {
        E13LeetCode20 s = new E13LeetCode20();
        System.out.println(s.isValid("()[]{}"));
        System.out.println("------------");
        System.out.println(s.isValid("()[]{"));
        System.out.println("------------");
        System.out.println(s.isValid("]["));
    }

    /**
     * 栈的应用
     * @param s
     * @return
     */
    public boolean isValid(String s) {
        ArraysStack<Character> stack = new ArraysStack<>(s.length());
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '(' -> {
                    stack.push(')');
                }
                case '[' -> {
                    stack.push(']');
                }
                case '{' -> {
                    stack.push('}');
                }
                default -> {
                   if (!stack.isEmpty() && c == stack.peek()) {
                       stack.pop();
                   } else {
                       return false;
                   }
                }
            }
        }
        return stack.isEmpty();
    }
}
